<?php
/**
 * Created by PhpStorm.
 * User: xufei
 * Date: 2018/5/9
 * Time: 下午3:10
 */

class wxapi_ctl_coupon extends wxapi_response{

    public function __construct(&$app) {
        parent::__construct($app);
    }

    /**
     * 领取优惠券列表
     */
    public function couponList()
    {
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        $objCoupon = app::get('b2c')->model('coupons');
        $couponList = $objCoupon->getUserCoupons();
        if (!empty($couponList)){
            foreach ($couponList as &$value){
                $arr_mem_coupon = app::get('b2c')->model('member_coupon')->getRow( '*',array('memc_code'=>$value['cpns_prefix'],'member_id'=>$member['member_id']) );
                $value['is_coupon'] = empty($arr_mem_coupon) ? 0 : 1;
                $value['from_time'] = date('Y-m-d', $value['from_time']);
                $value['to_time']   = date('Y-m-d', $value['to_time']);

            }
        }

        $return = [
            'result' => '',
            'data' => $couponList,
            'code' =>  0,
        ];
        return self::return_json($return);
    }


    private function get_current_member()
    {
        return self::user_auth();
    }

    /**
     * 获取可使用优惠券列表
     */
    public function useConponList()
    {
        $is_fastbuy = intval($_GET['is_fastbuy']);
        $member = $this->get_current_member();

        if(empty($member['member_id'])){
            return self::api_error('请先登录');
        }
        //获取已领取优惠券列表
        $oCoupon = kernel::single('b2c_coupon_mem');
        $couponList = $oCoupon->get_list_m($member['member_id']);

        //初始化返回信息
        $return_data = array(
            'valid'=>array(),
            'invalid'=>array()
        );

        //没有已领取优惠券
        if( empty($couponList) ){
            return self::return_json($return_data);
        }

        //基础验证 验证优惠券是否开始使用、是否过期、是否使用、是否禁用
        foreach( $couponList as $_key => $_val ) {
            $curTime = time();
            if ($curTime<$_val['time']['from_time'] || $curTime>=$_val['time']['to_time'] || $_val['memc_used_times'] || !$_val['coupons_info']['cpns_status']) {
                $return_data['invalid'][] = $_val;
                $_val['msg'] = '优惠券无效';
            }else{                
                $return_data['valid'][] = $_val;
            }
        }

        //如果无可用优惠券则直接返回
        if( empty($return_data['valid']) ){
            return self::return_json($return_data);
        }

        //验证优惠券是否可用于当前订单

        //模拟下购物车的数据。验证促销规则的时候需要用到
        $aData['is_fastbuy'] = $is_fastbuy;
        $aData['apply_platform'] = '1';
        $aCart = app::get('b2c')->model("cart")->get_objects($aData);  //获取购物车数据
        $discount_amount_order = $aCart['discount_amount_order'];
        $subtotal_price = $aCart['subtotal_prefilter_after'];
        $current_total = $subtotal_price - $discount_amount_order;
       
        unset($aCart['_cookie']);

        $obj_coupons = app::get('b2c')->model('coupons');
        $obj_cart_coupon = kernel::single('b2c_cart_object_coupon');
        $oCond = kernel::single('b2c_sales_order_aggregator_combine');

        //定义可用于微信小程序的优惠规则,目前只有现金抵扣和折扣可用
        // b2c_promotion_solutions_byfixed 满减
        // b2c_promotion_solutions_freeshipping 免邮
        // gift_promotion_solutions_gift 赠品
        // b2c_promotion_solutions_bypercent  减固定折扣
        // b2c_promotion_solutions_topercent 固定折扣
        // b2c_promotion_solutions_tofixed  固定价格
        $xcx_rule = array(
            'b2c_promotion_solutions_byfixed',
            'b2c_promotion_solutions_bypercent',
            'b2c_promotion_solutions_topercent',
            'b2c_promotion_solutions_tofixed'
        );

        foreach($return_data['valid'] as $ckey=>$cval){
            $aCart['object']['coupon'] = array(); //初始化优惠券信息
            $objIdent = "coupon_".$cval['memc_code'];
            $aCouponRule = $obj_coupons->getCouponByCouponCode($cval['memc_code']);
            $arr = app::get('b2c')->model('sales_rule_order')->getList( '*',array('rule_id'=>$aCouponRule[0]['rule_id']) );
            $rule_type = array_keys($arr[0]['action_solution'])[0];
           
            //不在指定规则的暂设为不可用
            if( !in_array($rule_type, $xcx_rule) ){
                $cval['msg'] = '当前优惠只支持现金类优惠';
                $return_data['invalid'][] = $cval;
                unset($return_data['valid'][$ckey]);
                continue;
            }
            $usedCoupon = $obj_cart_coupon->getAll();

            $coupon_info = array(
                'obj_ident'    => $objIdent,
                'obj_type' => 'coupon',
                'quantity' => 1,
                'description' => '',
                'coupon' => $cval['memc_code'],
                'rule_id'   => $aCouponRule[0]['rule_id'],
                'cpns_id'   => $aCouponRule[0]['cpns_id'],
                'cpns_type' => $aCouponRule[0]['cpns_type'],
                'name'  =>  '',
            );
            $aCart['object']['coupon'][] = $coupon_info;
            //模拟下促销规则验证,老规则如果验证失败了。不做处理
            
            $conditions = $arr[0]['conditions'];
            $validate = $oCond->validate($aCart,$conditions);

            if( $validate ){
                $status = true;
                $fail = 0;
                $aggregator = $conditions['conditions']['1']['aggregator'];
                $main_conditions = $conditions['conditions']['1']['conditions'];
                $rule_count = count($main_conditions);
                
                //注销验证失败的规则
                foreach( $main_conditions as $key=>$rule ){
                    if( $rule['attribute'] == 'order_subtotal' ){
                        $status = $obj_cart_coupon->valid_order_subtotal($rule,$current_total);
                        if( !$status ){
                            $fail++;
                            unset($conditions['conditions']['1']['conditions'][$key]);
                        }
                    }
                }

                if( $fail ){
                    //如果还剩余规则，则再验证剩余规则（如果没有剩余规则，验证时会返回ture，好尴尬）,主要用于组合条件的促销
                    if( $conditions['conditions']['1']['conditions'] && $$aggregator == 'any' ){
                        $validate = $oCond->validate($aCart,$conditions);
                    }else{
                        $validate = false;
                    }
                    if( !$validate ){
                        $cval['msg'] = '不满足该优惠券的使用条件！';
                        $return_data['invalid'][] = $cval;
                        unset($return_data['valid'][$ckey]);
                        continue;
                    }
                }
            }

            if( !$arr || !is_array($arr) ) {
                $cval['msg'] = '优惠券信息错误！';
                $return_data['invalid'][] = $cval;
                unset($return_data['valid'][$ckey]);
                continue;
            }
            reset( $arr );
            $arr = current( $arr );
            if( $arr['status']!=='true' ) {
                $cval['msg'] = '该优惠券不能使用！！活动未开启！';
                $return_data['invalid'][] = $cval;
                unset($return_data['valid'][$ckey]);
                continue;
            }
            $curtime = time();
            if( $curtime<$arr['from_time'] || $curtime>$arr['to_time']  ) {
                $cval['msg'] = '该优惠券不在可使用时间内，或者已过期！';
                $return_data['invalid'][] = $cval;
                unset($return_data['valid'][$ckey]);
                continue;
            }

            if($arr['stop_rules_processing'] == 'true' && count($usedCoupon) > 0 ){
                $cval['msg'] = '该优惠券无法与其他优惠券同时使用！';
                $return_data['invalid'][] = $cval;
                unset($return_data['valid'][$ckey]);
                continue;
            }

            foreach($usedCoupon as $key => $value){
                $curRule = app::get('b2c')->model('sales_rule_order')->getList( '*',array('rule_id'=>$value['params']['rule_id']) );
                if( !$curRule || !is_array($curRule) ) {
                    $cval['msg'] = '优惠券信息错误！';
                    $return_data['invalid'][] = $cval;
                    unset($return_data['valid'][$ckey]);
                    continue;
                }
                reset( $curRule );
                $curRule = current( $curRule );
                if($curRule['stop_rules_processing'] == 'true'){
                    $cval['msg'] = '已添加的优惠券无法与其他优惠券同时使用！';
                    $return_data['invalid'][] = $cval;
                    unset($return_data['valid'][$ckey]);
                    continue;
                }
            }
        }
        // echo "<pre>";var_dump($return_data);exit;
        return self::return_json($return_data);
    }

    /**
     * 使用优惠券 计算金额
     * @params coupon 优惠券编码
     * @is_fastbuy 立即购买
     */
    public function useCoupon()
    {
        // $_GET['coupon'] = 'B111222DFB3300001'; 
        // $_POST['is_fastbuy'] = 'true';
        $aData = $_GET;
        
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            return self::api_error('请先登录');
        }
        
        $arr_objects = array();
        if ($objs = kernel::servicelist('b2c_cart_object_apps'))
        {
            foreach ($objs as $obj)
            {
                if( $obj->get_type() != 'coupon') continue;
                if ($obj->need_validate_store()){
                    $arr_objects[$obj->get_type()] = $obj;
                }
            }
        }

        $type = 'coupon';
        $aData['apply_platform'] = '1';

        if (method_exists($arr_objects[$type], 'check_object'))
        {
            if (!$arr_objects[$type]->check_object($aData,$msg))
            {
                return self::api_error($msg);
            }
        }

        $obj_cart_object = kernel::single('b2c_cart_objects');
        if( !isset($aData['is_fastbuy']) || $aData['is_fastbuy'] ){
            $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg,true);
        }else{
            $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg);
        }

        if( !$obj_ident ){
            return self::api_error($msg);
        }
        
        //获取订单价格
        $totalPrice = kernel::single('wxapi_respositories_cart_cart')->get_cart_price();

        $aCart = app::get('b2c')->model("cart")->get_objects($aData);  //获取购物车数据

        $promotion_coupon = $aCart['promotion']['coupon'];
        $promotion_coupon1 = $aCart['object']['coupon'];

        // echo "<pre>";var_dump($promotion_coupon,$promotion_coupon1);exit;

        $return_data = [
            'code' =>0,
            'result' => '优惠券使用成功',
            'data' => array('obj_ident'=>$obj_ident,'promotion_coupon'=>$promotion_coupon),
            'totalPrice' => $totalPrice['subtotal'],
            'reduceFee' => $totalPrice['discount_amount'],
        ];
        
        return self::return_json($return_data);
    }  

}